const app = getApp()
const util = require("../../utils/util.js")
/* goods_id: 1181888  product_id: 1 */
Page({

  data: {
    userInfo: {},
    boolSelectAll: 1,
    hasUserInfo: false,
    hasAddrList: false,
    cartList: [1],
    cartTotal: '',
  },

  /**
   * User Functions
  */
  createOrder:function() {
    if (this.data.hasAddrList) {
      wx.navigateTo({
        url: "/pages/userSpace/orderCheck/orderCheck"
      })
    } else {
      wx.navigateTo({
        url: "/pages/userSpace/address/address"
      })
    }
  },
  addGoodsItem: function(event) {
    let gid = event.currentTarget.dataset.info.goods_id;
    let pid = event.currentTarget.dataset.info.product_id;
    // console.log(gid, pid);
    let _this = this;
    util.myRequest({
      url: util.api.cartAdd,
      method: 'post',
      data: {
        goodsId: gid,
        number: 1,
        productId: pid
      },
      success: res => {
        console.log("item++ success", res.data)
        _this.setData({ cartList: res.data.cartList, cartTotal: res.data.cartTotal})
      }
    })

  },
  delGoodsItem:function(event) {
    let _this = this;
    wx.showModal({
      title: '是否删除该商品',
      content: '商品将从你的购物车移除',
      success (res) {
        if (res.confirm) {
          let pid = '' + event.currentTarget.dataset.pid;
          util.myRequest({
            url: util.api.cartDelete,
            method: "post",
            data: { productIds: pid },
            success: res =>{
              _this.setData({ cartList: res.data.cartList, cartTotal: res.data.cartTotal })
            }
          });
        } else if (res.cancel) {}
      }
    })

  },
  subGoodsItem: function(event) {
    let id = event.currentTarget.dataset.info.id;
    let goodsId = event.currentTarget.dataset.info.goods_id;
    let number = event.currentTarget.dataset.info.number-1;
    if( number<=1 ){number = 1};
    let productId = event.currentTarget.dataset.info.product_id;
    let _this = this;
    util.myRequest({
      url: util.api.cartUpdate,
      method: "POST",
      data: {
        id, goodsId, number, productId
      },
      success: res =>{
        console.log(res)
        _this.setData({ cartList: res.data.cartList, cartTotal: res.data.cartTotal })
      }
    })
  },
  checkedProduct: function(e) {
    let idx = e.currentTarget.dataset.idx;
    let lastChecked = this.data.cartList[idx].checked;
    let currentChecked = (!!lastChecked)?(0):(1);
    let _this = this;
    let productIds = e.currentTarget.dataset.info.product_id;
    let isChecked = currentChecked;
    util.myRequest({
      url: util.api.cartChecked,
      method: "post",
      data: { productIds, isChecked },
      success: res =>{
        _this.setData({ cartList: res.data.cartList, cartTotal: res.data.cartTotal });
        _this.checkIsSelectAll();
      }
    })
  },
  selectAll: function() {
    let currentSelectAll = (!!this.data.boolSelectAll)?(0):(1);
    let productIds = this.getAllProductIds();
    let isChecked = currentSelectAll;
    let _this = this;
    util.myRequest({
      url: util.api.cartChecked,
      method: "post",
      data: { productIds, isChecked },
      success: res =>{
        _this.setData({ cartList: res.data.cartList, cartTotal: res.data.cartTotal });
        _this.checkIsSelectAll();
      }
    })
  },
  /**
   * test functions: 
   *  1. printGoods()
   *  2. addGoods()
   *  3. printCard()
  */
  printGoods: function() {
    util.myRequest({
      url: util.api.goodsDetail,
      data: { id: 1147048 },
      success: res=> {
        console.log("printGoods", res)
      }
    })
  },

  addGoods: function() {
    util.addGoods( 1147048, 1, 228 );
  },

  printCard: function() {
    util.myRequest({
      url: util.api.cartIndex,
      success: res => {
        console.log("printCard", res)
      }
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  updateCart: function() {
    var _this = this;
    util.myRequest({
      url: util.api.cartIndex,
      success: (res) =>{
        _this.setData({
          cartList: res.data.cartList,
          cartTotal: res.data.cartTotal
        });
        _this.checkIsSelectAll();
      }
    })
  },

  setHasAddr: function() {
    let _this = this;
    util.myRequest({
      url: util.api.addressList,
      success: (res) =>{
        let bool = !!res.data[0];
        _this.setData({
          hasAddrList: bool
        })
      }
    })
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let token = wx.getStorageSync('token');
    let userInfo = wx. getStorageSync('userInfo')
    if(!!token){
      console.log("userPage 已登录")

      this.setData({
        userInfo: userInfo,
        hasUserInfo: false
      })
      this.updateCart();
      this.setHasAddr();
    } else {
      wx.navigateTo({
        url: "/pages/login/login"
      })
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },
  
  /**
   * combine product_ids
  */
  getAllProductIds: function() {
    let arrIDs = [];
    for (let index = 0; index < this.data.cartList.length; index++) {
      let element =  this.data.cartList[index];
      arrIDs.push(element.product_id);
    }
    return arrIDs.join(',')
  },

  checkIsSelectAll: function() {
    let my_checked = 1;
    for (let index = 0; index < this.data.cartList.length; index++) {
      let element =  this.data.cartList[index];
      my_checked = my_checked & element.checked;
    }
    this.setData({
      boolSelectAll: my_checked
    })
  },
  
  toIndex: function() {
    wx.switchTab({
      url: '/pages/index/index'
    })
  }
})